package com.lagou.edu.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.lagou.edu.annotation.Service;
import com.lagou.edu.pojo.DataConfig;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author 应癫
 */
@Service("connectionUtils")
public class ConnectionUtils {

    /*private ConnectionUtils() {

    }

    private static ConnectionUtils connectionUtils = new ConnectionUtils();

    public static ConnectionUtils getInstance() {
        return connectionUtils;
    }*/


    private ThreadLocal<Connection> threadLocal = new ThreadLocal<>(); // 存储当前线程的连接

    /**
     * 从当前线程获取连接
     */
    public Connection getCurrentThreadConn() throws SQLException {
        /**
         * 判断当前线程中是否已经绑定连接，如果没有绑定，需要从连接池获取一个连接绑定到当前线程
          */
        Connection connection = threadLocal.get();
        if(connection == null) {
            // 从连接池拿连接并绑定到线程
            ZkClient zkClient = DruidUtils.getZkClient();
            DataConfig dataConfig = zkClient.readData(ZookeeperUtil.ROOT_PATH);
            DruidDataSource instance = DruidUtils.getInstance(dataConfig);
            connection = instance.getConnection();
            // 绑定到当前线程
            threadLocal.set(connection);

            zkClient.subscribeDataChanges(ZookeeperUtil.ROOT_PATH, new IZkDataListener() {
                @Override
                public void handleDataChange(String s, Object o) throws Exception {
                    System.out.println(s+"节点数据发生变化："+o);
                    instance.close();
                    DataConfig newDbConfig = (DataConfig)o;
                    DruidDataSource newinstance = DruidUtils.getInstance(newDbConfig);
                    Connection newconnection1 = newinstance.getConnection();
                    threadLocal.set(newconnection1);
                }

                @Override
                public void handleDataDeleted(String s) throws Exception {
                    System.out.println(s+"节点数据被删除");
                    if(!zkClient.exists(ZookeeperUtil.ROOT_PATH)) {
                        DataConfig dataConfig = new DataConfig();
                        dataConfig.setDriverClassName("com.mysql.jdbc.Driver");
                        dataConfig.setUrl("jdbc:mysql://localhost:3306/bank?autoReconnect=true&useSSL=false&characterEncoding=utf-8");
                        dataConfig.setUsername("root");
                        dataConfig.setPassword("root");
                        zkClient.createPersistent(ZookeeperUtil.ROOT_PATH,dataConfig);

                    }
                }
            });


        }

        return connection;

    }
}
